// src/UserSelector.tsx
import React, { useState } from 'react';
import { Select, Spin } from 'antd';
import axios from 'axios';

interface User {
    UserName: string;
    UserAge: number;
}

const { Option } = Select; // 从 Select 中解构 Option

const UserSelector: React.FC = () => {
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const fetchUsers = async (keyWord: string) => {
        setLoading(true);
        setError(null);
        try {
            const response = await axios.get('https://m1.apifoxmock.com/m1/6521928-6222613-default/getUser', {
                params: { keyWord },
            });
            const data = response.data.Response;

            if (data.Code) {
                setError(data.Message);
            } else {
                setUsers(data.Data);
            }
        } catch (err) {
            setError('网络错误');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Select
            showSearch
            placeholder="选择用户"
            filterOption={false}
            onSearch={fetchUsers}
            notFoundContent={loading ? <Spin size="small" /> : error || '未找到用户'}
        >
            {users.map((user) => (
                <Option key={user.UserName} value={user.UserName}>
                    {user.UserName} ({user.UserAge}岁)
                </Option>
            ))}
        </Select>
    );
};

export default UserSelector;
